package top.dingyingying.springboot3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.dingyingying.springboot3.base.PageBean;
import top.dingyingying.springboot3.base.R;
import top.dingyingying.springboot3.dao.TbClassMapper;
import top.dingyingying.springboot3.dao.TbStudentMapper;
import top.dingyingying.springboot3.entity.TbClass;
import top.dingyingying.springboot3.entity.TbStudent;
import top.dingyingying.springboot3.service.TbStudentService;
import top.dingyingying.springboot3.vo.PageVo;


@Service
@Slf4j
@RequiredArgsConstructor
public class TbStudentServiceImpl implements TbStudentService {
    private final TbStudentMapper tbStudentMapper;
    private final TbClassMapper tbClassMapper;


    @Override
    public R<String> insert(TbStudent tbStudent) {
//        验证班级信息是否正确
        TbClass check = tbClassMapper.selectById(tbStudent.getClassId());
        if (check == null) {
            return R.fail("班级信息错误", null);
        }
        int i = tbStudentMapper.insert(tbStudent);
        return i == 1 ? R.ok("新增成功", null) : R.fail("新增失败", null);
    }

    @Override
    public R<PageVo<TbStudent>> query(TbStudent tbStudent, PageBean pageBean) {
        IPage<TbStudent> page = new Page<>(pageBean.getPageNumber(), pageBean.getPageSize());
        QueryWrapper<TbStudent> wrapper = new QueryWrapper<>();
//      班级查询
        wrapper.eq(tbStudent.getClassId() != null,
                "class_id", tbStudent.getClassId());

//      姓名模糊查询
        wrapper.like(StringUtils.hasText(tbStudent.getName()),
                "name", tbStudent.getName());
        page = tbStudentMapper.selectPage(page, wrapper);
        return R.ok(page);
    }

    @Override
    public R<TbStudent> queryById(Integer id) {
        TbStudent tbStudent = tbStudentMapper.selectById(id);
        return tbStudent == null ?
                R.fail("查询失败", null) :
                R.ok("查询成功", tbStudent);
    }

@Override
    public R<String> update(TbStudent tbStudent) {
//        验证班级信息是否正确
        TbClass check = tbClassMapper.selectById(tbStudent.getClassId());
        if (check == null) {
            return R.fail("班级信息错误", null);
        }
        int i = tbStudentMapper.updateById(tbStudent);
        return i == 1 ? R.ok("修改成功", null) : R.fail("修改失败", null);
    }



    @Override
    public R<String> delete(Integer id) {
        int i = tbStudentMapper.deleteById(id);
        return i == 1 ? R.ok("删除成功", null) : R.fail("删除失败", null);
    }




























}
